/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.panpf.sketch.sample.util;

import me.panpf.sketch.util.Log;
import ohos.aafwk.content.Intent;
import ohos.utils.PlainArray;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * DataTransferStation
 */
public class DataTransferStation {
    private static final PlainArray<Map<String, Object>> PAGE_ARRAY = new PlainArray<>();

    private DataTransferStation() {
    }

    @NotNull
    private static String put(int pageId, @NotNull String dataFlag, @NotNull Object data) {
        // noinspection ConstantConditions
        if (data == null) {
            return null;
        }

        Optional<Map<String, Object>> optional = PAGE_ARRAY.get(pageId);
        Map<String, Object> dataMap = null;
        if (optional.isPresent()) {
            dataMap = optional.get();
        }
        if (dataMap == null) {
            dataMap = new HashMap<>();
            PAGE_ARRAY.put(pageId, dataMap);
        }

        String key = createKey(pageId, dataFlag);
        dataMap.put(key, data);

        return key;
    }

    private static void clean(int pageId) {
        Optional<Map<String, Object>> optional = PAGE_ARRAY.get(pageId);
        if (optional.isPresent()) {
            Map<String, Object> objectMap = optional.get();
            if (objectMap != null) {
                objectMap.clear();
            }
            PAGE_ARRAY.remove(pageId);
        }
    }

    @Nullable
    private static Object get(@Nullable String key) {
        if (key == null) {
            return null;
        }

        int pageId = parsePageIdFromKey(key);
        Optional<Map<String, Object>> optional = PAGE_ARRAY.get(pageId);
        if (optional.isPresent()) {
            Map<String, Object> dataMap = optional.get();
            if (dataMap != null) {
                return dataMap.get(key);
            }
        }
        return null;
    }

    @Nullable
    private static Object remove(@Nullable String key) {
        if (key == null) {
            return null;
        }

        int pageId = parsePageIdFromKey(key);
        Optional<Map<String, Object>> optional = PAGE_ARRAY.get(pageId);
        if (optional.isPresent()) {
            Map<String, Object> dataMap = optional.get();
            if (dataMap != null) {
                return dataMap.remove(key);
            }
        }
        return null;
    }

    private static String createKey(int pageId, @NotNull String dataFlag) {
        return pageId + "_" + dataFlag;
    }

    private static int parsePageIdFromKey(@NotNull String key) {
        String[] items = key.split("_");
        if (items.length != 2) {
            return -1;
        }

        try {
            return Integer.valueOf(items[0]);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * PageHelper
     */
    public static class PageHelper {
        private static final String PAGE_ID = "DATA_TRANSFER_STATION_PAGE_ID";
        private boolean forcedKill;
        private Object page;
        private int pageId = -1;

        public PageHelper(@NotNull Object page) {
            this.page = page;
        }

        /**
         * onCreate
         * @param onSaveInstanceState
         */
        public void onCreate(@Nullable Intent onSaveInstanceState) {
            forcedKill = false;

            if (onSaveInstanceState != null) {
                Object tempPageId = onSaveInstanceState.getParam(PAGE_ID);
                if (tempPageId == null) {
                    pageId = page.hashCode();
                } else {
                    pageId = (Integer) tempPageId;
                }
            } else {
                pageId = page.hashCode();
            }
        }

        /**
         * onSaveInstanceState
         *
         * @param outState
         */
        public void onSaveInstanceState(@NotNull Intent outState) {
            forcedKill = true;

            outState.setParam(PAGE_ID, pageId);
        }

        /**
         * onDestroy
         */
        public void onDestroy() {
            if (!forcedKill) {
                clean(pageId);
            }
        }

        /**
         * put
         *
         * @param dataFlag
         * @param data
         * @return String
         */
        @NotNull
        @SuppressWarnings("unused")
        public String put(@NotNull String dataFlag, @NotNull Object data) {
            return DataTransferStation.put(pageId, dataFlag, data);
        }

        /**
         * get
         *
         * @param key
         * @return Object
         */
        @Nullable
        @SuppressWarnings("unused")
        public Object get(@Nullable String key) {
            return DataTransferStation.get(key);
        }

        /**
         * remove
         *
         * @param key
         * @return Object
         */
        @Nullable
        @SuppressWarnings("unused")
        public Object remove(@Nullable String key) {
            return DataTransferStation.remove(key);
        }
    }
}
